﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace CMS_Tools.GeoNames
{
    public class GeonameDataBase
    {
        protected XmlElement xml;
        //public XmlDocument _doc;

        protected decimal ToDecimal(string str)
        {
            if (str == "")
                return 0;

            try
            {
                return XmlConvert.ToDecimal(str);
            }
            catch
            {
                return 0;
            }
        }

        protected int ToInt(string str)
        {
            if (str == "")
                return 0;

            try
            {
                return XmlConvert.ToInt32(str);
            }
            catch
            {
                return 0;
            }
        }

        protected DateTime ToDataTime(string str)
        {
            if (str == "")
                return DateTime.MinValue;

            try
            {
                return Convert.ToDateTime(str);
            }
            catch (Exception)
            {
                return DateTime.MinValue;
            }
        }

        protected string GetElement(XmlElement doc, string name)
        {
            XmlNodeList elements = doc.GetElementsByTagName(name);

            if (elements.Count == 0)
                return "";

            return elements[0].InnerXml;
        }


        protected string GetElementByAttributeValue(XmlElement doc, string name, string attrKey, string attrVal)
        {
            XmlNodeList elements = doc.GetElementsByTagName(name);

            if (elements.Count == 0)
                return "";

            foreach (XmlNode item in elements)
            {
                if (item.Attributes[attrKey].Value == attrVal)
                    return item.InnerXml;
            }

            return "";
        }

        protected string GetAttribute(XmlElement doc, string tagName, string attrKey)
        {
            XmlNodeList elements = doc.GetElementsByTagName(tagName);

            if (elements.Count == 0)
                return "";

            return elements[0].Attributes[attrKey] != null ? elements[0].Attributes[attrKey].Value : "";
        }

    }
}
